<template>
  <div ref="chart" style="width: 100%; height: 500px; background: #fff"></div>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { ref, inject, onMounted } from 'vue';

  import * as echarts from 'echarts';

  let echartsInstance = null;
  const echartsOption = {
    grid: {
      left: '20px',
      right: '20px',
      bottom: '10px',
      top: '60px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: true
      },
      alwaysShowContent: true,
      formatter: function (params) {
        let result = `${params[0].name}<br />`;

        result += `<p class="chart-tooltip-line2"><b>${params[1].marker} 总收益： </b><b>${params[1].data} 元</b></p>`;
        result += `<p class="chart-tooltip-line2"><b>${params[0].marker} 当日收益： </b><b>${params[0].data} 元</b></p>`;

        return result;
      }
    },
    legend: {
      show: true,
      selectedMode: false,
      data: ['每日收益', '总收益']
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: '{value}'
      },
      axisPointer: {
        show: true,
        label: {
          show: true,
          formatter: '{value}'
        }
      },
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '每日收益(单位：元)',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '总收益(单位：元)',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: `每日收益`,
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        itemStyle: {
          color: function (params) {
            if (params.value > 0) {
              return '#C1232B';
            } else {
              return 'green';
            }
          }
        }
      },
      {
        name: `总收益`,
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        itemStyle: {
          color: function (params) {
            if (params.value > 0) {
              return '#C1232B';
            }
          }
        },
        lineStyle: {
          width: 4
        }
      }
    ],
    visualMap: [
      {
        show: false,
        // 只对第一条线进行设置
        seriesIndex: 0,
        textStyle: {
          color: '#000'
        },
        pieces: [{ min: 0, max: 2000000, label: '涨', color: '#C1232B' }],
        outOfRange: {
          color: 'darkblue'
        }
      },
      {
        show: false,
        // 只对第二条线进行设置
        seriesIndex: 1,
        textStyle: {
          color: '#000'
        },
        pieces: [{ min: 0, max: 2000000, label: '涨', color: '#C1232B' }],
        outOfRange: {
          color: 'green'
        }
      }
    ]
  };

  const $store = useStore();
  const $http = inject('$http');
  const $eventBus = inject('$eventBus');

  const chart = ref();
  const profitTotals = ref([]);

  function renderIndexes() {
    $http.get(`/api/shares/daily/profit/totals`, { hideTip: true }).then(res => {
      let datas = res.datas || [0];
      let serieDatas = [datas[0].TotalRevenue];

      for (let index = 1; index < datas.length; index++) {
        serieDatas.push((datas[index].TotalRevenue - datas[index - 1].TotalRevenue).toFixed(2));
      }

      profitTotals.value = serieDatas;

      echartsOption.series[0].data = serieDatas;
      echartsOption.series[1].data = datas.map(m => m.TotalRevenue);
      echartsOption.xAxis.data = (res.datas || []).map(d => d.AccountingDate);

      echartsInstance.setOption(echartsOption);

      echartsInstance.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: echartsOption.xAxis.data.length - 1
      });
    });
  }

  function resizeChartPanel(area) {
    if (chart.value) {
      chart.value.style.width = area.width;
    }

    echartsInstance.resize();
  }

  onMounted(() => {
    $store.commit('navigateBack', { path: '/shares/list' });
    $store.commit('navigateTitle', `收益明细`);
    echartsInstance = echarts.init(chart.value);

    resizeChartPanel($store.state.area.content);

    renderIndexes();

    $eventBus.on('windowResizeChanged', client => resizeChartPanel(client));
  });
</script>
<style lang="less" scoped>
  :deep(.chart-tooltip-line2) {
    padding: 0;
    margin: 5px 0 0 0;
    min-width: 200px;
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    justify-content: space-between;

    > b {
      flex-grow: 1;

      &:first-of-type {
        text-indent: 0;
      }
    }
  }
</style>
